package me.ctidy.assignment06.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import me.ctidy.assignment06.R;
import me.ctidy.assignment06.util.MySQLiteOpenHelper;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "CTidy.SharedPreferences";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnSave = findViewById(R.id.save);
        btnSave.setOnClickListener((v) -> {
            // 1. 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);

            // 2. 获取 Editor 编辑器 对象
            SharedPreferences.Editor editor = sharedPreferences.edit();

            // 3. 写入数据
            editor.putString("username", "CTidy");
            editor.putString("password", "P@ssw0rd");

            // 4. 提交
            editor.commit();

            Log.d(TAG, "Save data successfully!");
            Toast.makeText(this, "Save data successfully!", Toast.LENGTH_LONG).show();
        });

        Button btnRead = findViewById(R.id.read);
        btnRead.setOnClickListener((v) -> {
            // 1. 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);

            // 2. 根据 key，获取相应的 value
            String username = sharedPreferences.getString("username", "NONE");
            String password = sharedPreferences.getString("password", "NONE");

            String msg = String.format("username = %s, password = %s", username, password);

            Log.d(TAG, msg);
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        });

        Button btnCreate = findViewById(R.id.db_create);
        btnCreate.setOnClickListener((v) -> {
            startActivity(new Intent(this, SQLiteActivity.class));
        });
    }
}
